import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

// Function to generate and write default information
const generateDefaultInfo = (packageVersion = '0.1.0') => {
  const defaultInfo = {
    version: packageVersion,
    lastUpdateDate: new Date().toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '/'),
    commitHash: 'N/A',
    commitMessage: 'Build from non-git environment',
    buildTime: new Date().toISOString()
  };

  const outputDir = path.join(process.cwd(), 'src', 'data');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const outputPath = path.join(outputDir, 'git-info.json');
  fs.writeFileSync(outputPath, JSON.stringify(defaultInfo, null, 2));

  console.log('⚠️ Git info not available, using default info:', defaultInfo);
};

try {
  // Check if .git directory exists. If not, it's not a git repo.
  const gitDir = path.join(process.cwd(), '.git');
  if (!fs.existsSync(gitDir)) {
    throw new Error('.git directory not found. This is not a git repository.');
  }

  // Read package.json to get the version
  const packageJsonPath = path.join(process.cwd(), 'package.json');
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));

  // Get git information
  const lastUpdateDate = execSync('git log -1 --format=%ad --date=format:%Y/%m/%d', { encoding: 'utf8', stdio: 'pipe' }).trim();
  const commitHash = execSync('git log -1 --format=%h', { encoding: 'utf8', stdio: 'pipe' }).trim();
  const commitMessage = execSync('git log -1 --format=%s', { encoding: 'utf8', stdio: 'pipe' }).trim();

  const gitInfo = {
    version: packageJson.version,
    lastUpdateDate,
    commitHash,
    commitMessage,
    buildTime: new Date().toISOString()
  };

  // Ensure the output directory exists
  const outputDir = path.join(process.cwd(), 'src', 'data');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  // Write the git info to a file
  const outputPath = path.join(outputDir, 'git-info.json');
  fs.writeFileSync(outputPath, JSON.stringify(gitInfo, null, 2));

  console.log('✅ Git info generated successfully:', gitInfo);

} catch (error) {
  console.error(`❌ Could not generate git info: ${error.message}`);
  
  // Attempt to read package.json for version even on failure
  let version = '0.1.0';
  try {
    const packageJsonPath = path.join(process.cwd(), 'package.json');
    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
    version = packageJson.version;
  } catch (pkgError) {
    console.error('Could not read package.json for version fallback.');
  }
  
  generateDefaultInfo(version);
}